/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dp1.titandevelop.titano.view.prod;

import dp1.titandevelop.titano.bean.Estado;
import dp1.titandevelop.titano.bean.Mensajes;
import dp1.titandevelop.titano.bean.RutaAux;
import dp1.titandevelop.titano.helper.UnidadMedida;
import dp1.titandevelop.titano.persistent.Proceso;
import dp1.titandevelop.titano.persistent.Produccion;
import dp1.titandevelop.titano.persistent.Producto;
import dp1.titandevelop.titano.persistent.ProductoXProceso;
import dp1.titandevelop.titano.persistent.Receta;
import dp1.titandevelop.titano.persistent.TipoProducto;
import dp1.titandevelop.titano.service.ProcesoService;
import dp1.titandevelop.titano.service.ProductoService;
import dp1.titandevelop.titano.service.ProductoXProcesoService;
import dp1.titandevelop.titano.service.RecetaService;
import dp1.titandevelop.titano.service.ValidacionService;
import dp1.titandevelop.titano.view.MensajeError;
import java.awt.Dimension;
import java.awt.Frame;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author Dorita
 */
public class ModulosT_PRO_ProductosNuevo1 extends javax.swing.JInternalFrame {
//Servicios
    ProductoService sp = new ProductoService();     
    RecetaService sr= new RecetaService();
    ProcesoService ps= new ProcesoService();
    ProductoXProcesoService spp = new ProductoXProcesoService();
    //private ArrayList<Producto> listaProductos;
    private ArrayList<TipoProducto> listaTipos;
    private List<Proceso> listaProceso;
    private ArrayList<Producto> listaInsumos;
    private ArrayList<Receta> listaReceta;
    
    private Mensajes sms = new Mensajes();
    
    private void addList (List<TipoProducto> tipo,List<Proceso> proc,List<String> ums){
        
        for(int i=0;i<tipo.size();i++){
            this.cmbTipoProducto.addItem(tipo.get(i).getDescripcion());
        }
        for(int i=0;i<proc.size();i++){
            this.cmbProceso.addItem(proc.get(i).getDescripcion());
        }
        for(int i=0;i<ums.size();i++){
            this.cmbUM.addItem(ums.get(i));
        }
    }

    /**
     * Creates new form ModulosT_ADM_ProductosNuevo
     */
    
    //Refrescar la tabla de productos
    public ModulosT_PRO_ProductosNuevo1(){
        initComponents();
        
        ValidacionService val = new ValidacionService();        
        val.SNumeros(this.txtLoteMax);
        val.Longitud(txtLoteMax,7);
        val.SNumeros(this.txtLoteMin);
        val.Longitud(txtLoteMin,4);
        val.SNumeros(this.txtStockMin);
        val.Longitud(txtStockMin,4);
        val.SNumeros(this.txtStockMax);
        val.Longitud(txtStockMax,7);
        val.SNumeros(this.txtDiasVencimiento);
        val.Longitud(txtDiasVencimiento,4);
        val.Longitud(this.txtBeneficio,7);
        val.Longitud(this.txtCosto,7);
        val.Longitud(this.txtPeso,7);
        this.listaInsumos = new ArrayList<Producto>();
        this.listaReceta = new ArrayList<Receta>();
        this.listaTipos = sp.buscarTodoLosTipos();//new ArrayList<TipoProducto>();
        this.listaProceso=ps.buscarProcAll();
        this.tablaReceta.setModel(this.modeloReceta);
        UnidadMedida u = new UnidadMedida();
        List<String> ums = u.getLista();
        addList(listaTipos,listaProceso,ums);
    }    
      
    public void RefrescarTablaReceta() {
        
        AbstractTableModel aux = (AbstractTableModel) this.tablaReceta.getModel();
       
        aux.fireTableDataChanged();
        }
    
    
    //Llena nuevos insumos a la lista de receta
    public void Llenar_Insumos(Producto p, float cantidad) {
        listaInsumos.add(p);
        //Crea el objeto receta para pasarlo a la lista a apartir del insumo ingresado
        Receta r =new Receta();
        r.setToProducto1(p); //--idmaterial
        r.setUm(p.getUm());
        Estado e=new Estado();
        r.setEstado(e.getActivo());
        r.setCantidad(cantidad);
        listaReceta.add(r);
        
       }    
        
    private AbstractTableModel modeloReceta = new AbstractTableModel() { // usando una clase anonima
        // colocando los titulos de las columnas

        String[] titles = {"Insumo", "Cantidad", "UM"};

        public String getColumnName(int col) {
            return titles[col];
        }

        public int getRowCount() {
            return listaReceta.size(); // cuantos registros (filas)
        }

        public int getColumnCount() {
            return 3; // cuantas columnas
        }

        public Object getValueAt(int rowIndex, int columnIndex) {
            String res = null;
            Receta r = listaReceta.get(rowIndex);
            switch (columnIndex) {
                case 0:
                    res =r.getToProducto1().getDescripcion();
                    break;
                case 1:
                    res = r.getCantidad().toString();
                    break;
                case 2:
                    res = r.getUm();
                    break;
                            }
            return res;
        }
        //Permite editar la columna de las cantidades
        @Override
            public boolean isCellEditable(int row, int column) {
           
                return ( column == 1 ); 
        }
     
        public void setValueAt(Object value, int row, int col) {
            if ( col == 1 ) {           
                Receta r=listaReceta.get(row);
                r.setCantidad(Float.parseFloat(""+value));
                listaReceta.set(row, r);
            }
            this.fireTableDataChanged();
        };
            
         

        public Receta getValue(int row) {
            return listaReceta.get(row);
        }

        
    };
    
    

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane1 = new javax.swing.JTabbedPane();
        btnGuardar = new javax.swing.JButton();
        btnSalir = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        lblProducto = new javax.swing.JLabel();
        txtProducto = new javax.swing.JTextField();
        lblTipoProducto = new javax.swing.JLabel();
        cmbTipoProducto = new javax.swing.JComboBox();
        lblStockMin = new javax.swing.JLabel();
        lblLoteMIn = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        lblCosto = new javax.swing.JLabel();
        lblDiasVenc = new javax.swing.JLabel();
        txtDiasVencimiento = new javax.swing.JTextField();
        txtCosto = new javax.swing.JTextField();
        txtPeso = new javax.swing.JTextField();
        txtLoteMin = new javax.swing.JTextField();
        txtStockMin = new javax.swing.JTextField();
        lblStockMax = new javax.swing.JLabel();
        lblLoteMax = new javax.swing.JLabel();
        lblUM = new javax.swing.JLabel();
        lblBeneficio = new javax.swing.JLabel();
        txtStockMax = new javax.swing.JTextField();
        txtLoteMax = new javax.swing.JTextField();
        cmbUM = new javax.swing.JComboBox();
        txtBeneficio = new javax.swing.JTextField();
        pnlReceta = new javax.swing.JPanel();
        jPanel9 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaReceta = new javax.swing.JTable();
        btnEliminaReceta = new javax.swing.JButton();
        btnDetalleReceta = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        cmbProceso = new javax.swing.JComboBox();

        setResizable(true);
        setTitle("Administración - Nuevo Producto");
        setMaximumSize(new java.awt.Dimension(685, 660));
        setMinimumSize(new java.awt.Dimension(685, 660));
        setPreferredSize(new java.awt.Dimension(685, 660));

        btnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/grabar.png"))); // NOI18N
        btnGuardar.setToolTipText("Guardar");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        btnSalir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/cancelar.png"))); // NOI18N
        btnSalir.setToolTipText("Salir");
        btnSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalirActionPerformed(evt);
            }
        });

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos"));

        lblProducto.setText("Producto");

        txtProducto.setFont(new java.awt.Font("Tekton Pro", 0, 11)); // NOI18N

        lblTipoProducto.setText("Tipo Producto");

        cmbTipoProducto.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Seleccionar" }));
        cmbTipoProducto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbTipoProductoActionPerformed(evt);
            }
        });

        lblStockMin.setText("Stock Min.");

        lblLoteMIn.setText("Lote Min.");

        jLabel2.setText("Peso");

        lblCosto.setText("Costo");

        lblDiasVenc.setText("Dias Vencimiento");

        txtDiasVencimiento.setFont(new java.awt.Font("Tekton Pro", 0, 11)); // NOI18N

        txtCosto.setFont(new java.awt.Font("Tekton Pro", 0, 11)); // NOI18N

        txtLoteMin.setFont(new java.awt.Font("Tekton Pro", 0, 11)); // NOI18N

        txtStockMin.setFont(new java.awt.Font("Tekton Pro", 0, 11)); // NOI18N

        lblStockMax.setText("Stock Max.");

        lblLoteMax.setText("Lote Max.");

        lblUM.setText("Unidad Medida");

        lblBeneficio.setText("Beneficio");

        txtStockMax.setFont(new java.awt.Font("Tekton Pro", 0, 11)); // NOI18N

        txtLoteMax.setFont(new java.awt.Font("Tekton Pro", 0, 11)); // NOI18N

        cmbUM.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Seleccionar" }));

        txtBeneficio.setFont(new java.awt.Font("Tekton Pro", 0, 11)); // NOI18N

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblDiasVenc)
                    .addComponent(lblCosto)
                    .addComponent(jLabel2)
                    .addComponent(lblLoteMIn)
                    .addComponent(lblStockMin)
                    .addComponent(lblProducto))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txtProducto, javax.swing.GroupLayout.DEFAULT_SIZE, 153, Short.MAX_VALUE)
                    .addComponent(txtDiasVencimiento)
                    .addComponent(txtCosto)
                    .addComponent(txtPeso)
                    .addComponent(txtLoteMin)
                    .addComponent(txtStockMin))
                .addGap(37, 37, 37)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblTipoProducto)
                    .addComponent(lblStockMax)
                    .addComponent(lblLoteMax)
                    .addComponent(lblUM)
                    .addComponent(lblBeneficio, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(38, 38, 38)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cmbUM, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(txtLoteMax)
                    .addComponent(txtStockMax)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addComponent(cmbTipoProducto, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(txtBeneficio))
                .addGap(8, 8, 8))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblProducto)
                    .addComponent(txtProducto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblTipoProducto)
                    .addComponent(cmbTipoProducto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblStockMin)
                    .addComponent(txtStockMin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblStockMax)
                    .addComponent(txtStockMax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblLoteMIn)
                    .addComponent(txtLoteMin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblLoteMax)
                    .addComponent(txtLoteMax, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(14, 14, 14)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(16, 16, 16)
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblCosto)
                            .addComponent(txtCosto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblBeneficio))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(lblDiasVenc)
                            .addComponent(txtDiasVencimiento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(txtPeso)
                            .addComponent(lblUM)
                            .addComponent(cmbUM, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtBeneficio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(40, 40, 40)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pnlReceta.setBorder(javax.swing.BorderFactory.createTitledBorder("Receta"));
        pnlReceta.setFont(new java.awt.Font("Tekton Pro", 0, 11)); // NOI18N
        pnlReceta.setPreferredSize(new java.awt.Dimension(660, 300));

        jPanel9.setBorder(javax.swing.BorderFactory.createTitledBorder("Lista de Insumos"));
        jPanel9.setPreferredSize(new java.awt.Dimension(617, 164));

        tablaReceta.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Descripcion", "Modulo", "Opcion"
            }
        ));
        tablaReceta.setPreferredSize(new java.awt.Dimension(600, 200));
        jScrollPane1.setViewportView(tablaReceta);

        btnEliminaReceta.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/eliminar.png"))); // NOI18N
        btnEliminaReceta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminaRecetaActionPerformed(evt);
            }
        });

        btnDetalleReceta.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/agregar.png"))); // NOI18N
        btnDetalleReceta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDetalleRecetaActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9);
        jPanel9.setLayout(jPanel9Layout);
        jPanel9Layout.setHorizontalGroup(
            jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel9Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 549, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnEliminaReceta, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnDetalleReceta, javax.swing.GroupLayout.Alignment.TRAILING)))
        );
        jPanel9Layout.setVerticalGroup(
            jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel9Layout.createSequentialGroup()
                .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel9Layout.createSequentialGroup()
                        .addComponent(btnDetalleReceta, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnEliminaReceta))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jLabel1.setText("Proceso:");

        cmbProceso.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Seleccionar" }));

        javax.swing.GroupLayout pnlRecetaLayout = new javax.swing.GroupLayout(pnlReceta);
        pnlReceta.setLayout(pnlRecetaLayout);
        pnlRecetaLayout.setHorizontalGroup(
            pnlRecetaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlRecetaLayout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(cmbProceso, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(pnlRecetaLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        pnlRecetaLayout.setVerticalGroup(
            pnlRecetaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlRecetaLayout.createSequentialGroup()
                .addGroup(pnlRecetaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cmbProceso, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel9, javax.swing.GroupLayout.PREFERRED_SIZE, 159, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(pnlReceta, javax.swing.GroupLayout.PREFERRED_SIZE, 653, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btnGuardar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnSalir)
                        .addGap(12, 12, 12))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pnlReceta, javax.swing.GroupLayout.PREFERRED_SIZE, 231, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(5, 5, 5)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(btnSalir)
                    .addComponent(btnGuardar))
                .addGap(8, 8, 8))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalirActionPerformed

        ModulosT_PRO_Productos admPro = new ModulosT_PRO_Productos();
        this.getParent().add(admPro);

        Dimension desktopSize = this.getParent().getSize();
        Dimension jInternalFrameSize = admPro.getSize();
        admPro.setLocation((desktopSize.width - jInternalFrameSize.width) / 2,
                (desktopSize.height - jInternalFrameSize.height) / 4);

        admPro.show();
        ModulosT_PRO.ventanaProductosNuevo=null;
        this.dispose();

    }//GEN-LAST:event_btnSalirActionPerformed

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
       // TODO add your handling code here:        
       //Inserta el producto y obtiene id
          ValidacionService val = new ValidacionService(); 
       if (!cmbTipoProducto.getSelectedItem().equals("Insumo")) {
                if(!val.esVacio(this.txtBeneficio)&&
               !val.esVacio(this.txtCosto)&&
               !val.esVacio(this.txtDiasVencimiento)&&
               !val.esVacio(this.txtLoteMax)&&
               !val.esVacio(this.txtLoteMin)&&
               !val.esVacio(this.txtPeso)&&
               !val.esVacio(this.txtProducto)&&
               !val.esVacio(this.txtStockMax)&&
               !val.esVacio(this.txtStockMin)&&
               !val.esCBoxVacio(cmbUM)&&
               !val.esCBoxVacio(cmbTipoProducto)&&!val.esCBoxVacio(this.cmbProceso)&&!this.listaReceta.isEmpty()){ 
        
           try{
            int idProceso =0;
            if(!val.esCBoxVacio(cmbProceso)) {
                ProcesoService pss = new ProcesoService();
                Proceso proc1 = pss.buscarPorDescripcion((String)this.cmbProceso.getSelectedItem());
                idProceso = proc1.getIdproceso();}
           
                int prod = this.sp.insertar((String) cmbTipoProducto.getSelectedItem(),
                        this.txtProducto.getText(), Integer.parseInt(this.txtStockMin.getText()), 
                        Integer.parseInt(this.txtStockMax.getText()), Integer.parseInt(this.txtLoteMin.getText()), 
                        Integer.parseInt(this.txtLoteMax.getText()),Integer.parseInt(this.txtDiasVencimiento.getText()),
                        Float.parseFloat(this.txtBeneficio.getText()), Float.parseFloat(this.txtCosto.getText()), 
                        (String)this.cmbUM.getSelectedItem(), idProceso,
                        Float.parseFloat(this.txtPeso.getText()));

                //Si es insumo insertar proveedores, si no insertar receta
                if (!cmbTipoProducto.getSelectedItem().equals("Insumo")) 
                    this.sr.Insertar(prod, listaReceta); 

                if (cmbTipoProducto.getSelectedItem().equals("Producto Terminado")) {
                // Agregar a tabla ProductoXProceso
                //Llenamos Ruta
                ArrayList<RutaAux> a = new ArrayList<RutaAux>();
                Producto producto = this.sp.buscarPorId(prod);
                llenaRuta (producto, a);
                //Lleno para todos los procesos del producto...
                    for (int i=0; i<a.size();i++)
                    {
                        //Todos los productos de salida
                        for (int j=0;j<a.get(i).listaSalidas.size();j++)
                            this.spp.Inserta(a.get(i).proceso.getIdproceso(), a.get(i).orden, 1, producto.getIdproducto(), a.get(i).listaSalidas.get(j).getIdproducto());
                        //Todos los productos de entrada
                        for (int j=0;j<a.get(i).listaEntradas.size();j++)
                            this.spp.Inserta(a.get(i).proceso.getIdproceso(), a.get(i).orden, 0, producto.getIdproducto(), a.get(i).listaEntradas.get(j).getIdproducto());
                    }
                } 
                JOptionPane.showInternalMessageDialog(this.getRootPane(),sms.getRegistrado(),"Mensaje",JOptionPane.INFORMATION_MESSAGE);
            
                ModulosT_PRO.AdmProductos = new ModulosT_PRO_Productos();
                this.getParent().add(ModulosT_PRO.AdmProductos);
                Dimension desktopSize = this.getParent().getSize();
                Dimension jInternalFrameSize =  ModulosT_PRO.AdmProductos.getSize();
                ModulosT_PRO.AdmProductos.setLocation((desktopSize.width - jInternalFrameSize.width) / 2,
                        (desktopSize.height - jInternalFrameSize.height)/4 );
                ModulosT_PRO.AdmProductos.show();
                ModulosT_PRO.ventanaProductosNuevo=null;
                this.dispose(); 

           } catch(Exception e) {
                   //e.printStackTrace();
                    JOptionPane.showInternalMessageDialog(this.getRootPane(),sms.getError(),"Error",JOptionPane.ERROR_MESSAGE);
              }
          }
          else{
              JOptionPane.showInternalMessageDialog(this.getRootPane(),sms.getCompletarCampos(), "Aviso", JOptionPane.WARNING_MESSAGE);
          }
       }
       else 
       {
         if(!val.esVacio(this.txtBeneficio)&&
               !val.esVacio(this.txtCosto)&&
               !val.esVacio(this.txtDiasVencimiento)&&
               !val.esVacio(this.txtLoteMax)&&
               !val.esVacio(this.txtLoteMin)&&
               !val.esVacio(this.txtPeso)&&
               !val.esVacio(this.txtProducto)&&
               !val.esVacio(this.txtStockMax)&&
               !val.esVacio(this.txtStockMin)&&
               !val.esCBoxVacio(cmbUM)&&
               !val.esCBoxVacio(cmbTipoProducto)) 
         {
              try{
                 int idProceso =0;
                 if (this.ps.buscarPorId(0)== null)
                {
                    ps.CreaProcesoBase();
                } 
                    int prod = this.sp.insertar((String) cmbTipoProducto.getSelectedItem(),
                        this.txtProducto.getText(), Integer.parseInt(this.txtStockMin.getText()), 
                        Integer.parseInt(this.txtStockMax.getText()), Integer.parseInt(this.txtLoteMin.getText()), 
                        Integer.parseInt(this.txtLoteMax.getText()),Integer.parseInt(this.txtDiasVencimiento.getText()),
                        Float.parseFloat(this.txtBeneficio.getText()), Float.parseFloat(this.txtCosto.getText()), 
                        (String)this.cmbUM.getSelectedItem(), idProceso,
                        Float.parseFloat(this.txtPeso.getText()));
                    JOptionPane.showInternalMessageDialog(this.getRootPane(),sms.getRegistrado(),"Mensaje",JOptionPane.INFORMATION_MESSAGE);
            
                ModulosT_PRO.AdmProductos = new ModulosT_PRO_Productos();
                this.getParent().add(ModulosT_PRO.AdmProductos);
                Dimension desktopSize = this.getParent().getSize();
                Dimension jInternalFrameSize =  ModulosT_PRO.AdmProductos.getSize();
                ModulosT_PRO.AdmProductos.setLocation((desktopSize.width - jInternalFrameSize.width) / 2,
                        (desktopSize.height - jInternalFrameSize.height)/4 );
                ModulosT_PRO.AdmProductos.show();
                ModulosT_PRO.ventanaProductosNuevo=null;
                this.dispose(); 
           } catch(Exception e) {
                   //e.printStackTrace();
                    JOptionPane.showInternalMessageDialog(this.getRootPane(),sms.getError(),"Error",JOptionPane.ERROR_MESSAGE);
              }
          }
          else{
              JOptionPane.showInternalMessageDialog(this.getRootPane(),sms.getCompletarCampos(), "Aviso", JOptionPane.WARNING_MESSAGE);
          }

       }       
          

    }//GEN-LAST:event_btnGuardarActionPerformed
 private void llenaRuta (Producto prod, ArrayList<RutaAux> a)
    {
         ArrayList<Receta> lr = this.sr.BuscarPorProducto(prod);//me bota las entradas para un producto
            if (a.isEmpty()){
                    RutaAux ruta= new RutaAux();
                    ruta.proceso=prod.getToProceso();
                    ruta.orden=1;
                    ruta.listaSalidas.add(prod);
                    for (int i=0; i<lr.size();i++)
                    {
                        ruta.listaEntradas.add(lr.get(i).getToProducto1());//Agrega todos los insumos para el producto
                        if (lr.get(i).getToProducto1().getToTipoProducto().getIdtipoproducto()!=1) //return
                           llenaRuta (lr.get(i).getToProducto1(),a);
                    }
                    a.add(ruta);
                    a.get(a.size()-1).orden=a.size();
                                        
            }
            else 
                for (int i=0;i<a.size();i++)
                {
                    if(a.get(i).proceso==prod.getToProceso())
                    {  a.get(i).listaSalidas.add(prod);
                        for (int j=0; j<lr.size();j++)
                        {
                            a.get(i).listaEntradas.add(lr.get(j).getToProducto1());//Agrega todos los insumos para el producto
                            if (lr.get(j).getToProducto1().getToTipoProducto().getIdtipoproducto()!=1) //return
                                llenaRuta (lr.get(j).getToProducto1(),a);
                        } 
                        
                     }
                    else{
                        RutaAux ruta= new RutaAux();
                        ruta.proceso=prod.getToProceso();
                        ruta.orden=1;
                        ruta.listaSalidas.add(prod);
                        for (int j=0; j<lr.size();j++)
                        {
                            ruta.listaEntradas.add(lr.get(j).getToProducto1());//Agrega todos los insumos para el producto
                            if (lr.get(i).getToProducto1().getToTipoProducto().getIdtipoproducto()!=1) //return
                                llenaRuta (lr.get(j).getToProducto1(),a);
                        }  
                        a.add(ruta);
                        a.get(a.size()-1).orden=a.size();
                    }
                }
          
       
    }              
    private void cmbTipoProductoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbTipoProductoActionPerformed
        // TODO add your handling code here:
        if ("Insumo".equals((String) cmbTipoProducto.getSelectedItem())) {
            txtBeneficio.setText("0");
            txtBeneficio.setEnabled(false);
            txtLoteMin.setEnabled(true);
            txtLoteMax.setEnabled(true);
            this.cmbProceso.setEnabled(false);
            this.btnDetalleReceta.setEnabled(false);
            this.btnEliminaReceta.setEnabled(false);
            this.listaReceta.clear();
            this.RefrescarTablaReceta();
            

        } else {
            txtBeneficio.setEnabled(true);
            txtLoteMin.setEnabled(false);
            txtLoteMax.setEnabled(false);
            txtLoteMin.setText("0");
            txtLoteMax.setText("0");
            this.cmbProceso.setEnabled(true);
            this.btnDetalleReceta.setEnabled(true);
            this.btnEliminaReceta.setEnabled(true);
            
          
        }
    }//GEN-LAST:event_cmbTipoProductoActionPerformed

    private void btnEliminaRecetaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminaRecetaActionPerformed
        // Elimina un detalle de la receta
 // TODO add your handling code here:
       // listaEliminados.add(this.listaReceta.get(tablaReceta.getSelectedRow()));
        listaReceta.remove(this.tablaReceta.getSelectedRow());
        this.RefrescarTablaReceta();
    }//GEN-LAST:event_btnEliminaRecetaActionPerformed

    private void btnDetalleRecetaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDetalleRecetaActionPerformed
        // TODO add your handling code here:
        Frame f = JOptionPane.getFrameForComponent(this);
        ModulosT_PRO_BuscarProducto dialog = new ModulosT_PRO_BuscarProducto(f,true, listaInsumos,1, null);
        //this.getParent().add(dialog);
        dialog.setVisible(true);
    }//GEN-LAST:event_btnDetalleRecetaActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnDetalleReceta;
    private javax.swing.JButton btnEliminaReceta;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JButton btnSalir;
    private javax.swing.JComboBox cmbProceso;
    private javax.swing.JComboBox cmbTipoProducto;
    private javax.swing.JComboBox cmbUM;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JLabel lblBeneficio;
    private javax.swing.JLabel lblCosto;
    private javax.swing.JLabel lblDiasVenc;
    private javax.swing.JLabel lblLoteMIn;
    private javax.swing.JLabel lblLoteMax;
    private javax.swing.JLabel lblProducto;
    private javax.swing.JLabel lblStockMax;
    private javax.swing.JLabel lblStockMin;
    private javax.swing.JLabel lblTipoProducto;
    private javax.swing.JLabel lblUM;
    private javax.swing.JPanel pnlReceta;
    private javax.swing.JTable tablaReceta;
    private javax.swing.JTextField txtBeneficio;
    private javax.swing.JTextField txtCosto;
    private javax.swing.JTextField txtDiasVencimiento;
    private javax.swing.JTextField txtLoteMax;
    private javax.swing.JTextField txtLoteMin;
    private javax.swing.JTextField txtPeso;
    private javax.swing.JTextField txtProducto;
    private javax.swing.JTextField txtStockMax;
    private javax.swing.JTextField txtStockMin;
    // End of variables declaration//GEN-END:variables
}
